package com.dongzili.common.config.satoken;

import cn.dev33.satoken.exception.NotLoginException;
import cn.dev33.satoken.interceptor.SaInterceptor;
import cn.dev33.satoken.stp.StpUtil;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import java.util.Arrays;
import java.util.List;

@Configuration
public class SatokenConfigure implements WebMvcConfigurer {

    @Resource
    HttpServletRequest request;
    @Resource
    HttpServletResponse response;

    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        registry.addInterceptor(new SaInterceptor(handler ->{
            System.out.println(request.getRequestURL());

//                    Enumeration<String> enumeration = request.getHeaderNames();
//                    System.out.println("headers: "+ JSONUtil.toJsonStr(enumeration));
                    System.out.println("satoken: "+request.getHeader("satoken"));
            List<String> uri = Arrays.asList("/.well-known/appspecific/com.chrome.devtools.json", "/error");
            try {
                if(!uri.contains(request.getRequestURI()) && !StpUtil.isLogin()){
                    throw new NotLoginException(request.getRequestURI()+" 未登录或登录信息已过期，请重新登录！", "", "");
                }
            }catch (Exception e){
                throw new NotLoginException(request.getRequestURI()+" 未登录或登录信息已过期，请重新登录！", "", "");
            }

        })
        .isAnnotation(true))
        .addPathPatterns("/**")
        .excludePathPatterns(
                "/auth/login",
                "/auth/logout",
                "/favicon.ico",
//                "/rules/startGenerateSse",
//                "/sse/onlineTime",
                "/",
                "/index.html",
                "/assets/**",
                "/web/**",
                "/disruptor/**",
                "/gnnu/**"
        )
        ;
    }
}
